import React, {Component} from 'react';
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheQueryForm from '@/components/TheQueryForm';
import TheImage from '@/components/TheImage'
import {Modal, Form, Button, Space, message, InputNumber} from 'antd'
import { goodsInfoPage } from '@/request/storeBackManage/goodsManage/centerGoodsList';
import { apiGetHomeGoodsSortDetail,apiAddHomeGoodsSort,apiGetStoreGoodsPage } from '@/request/app/homeFeatured';

class SelectGoods extends Component {
    constructor(props) {
        super(props)
        this.state = {
            columns: [
                {
                    title: "商品ID",
                    key: "goodsId",
                    width: 100,
                    dataIndex: "goodsId",
                },
                {
                    title: "商品名称",
                    key: "goodsName",
                    dataIndex: "goodsName",
                    onCell: () => {
                        return {
                            style: {
                                maxWidth: 160,
                                overflow: 'hidden',
                                whiteSpace: 'nowrap',
                                textOverflow: 'ellipsis',
                                cursor: 'pointer'
                            }
                        }
                    }
                },
                {
                    title: "商品图片",
                    key: "goodsShowImages",
                    dataIndex: "goodsShowImages",
                    render: (text) => {
                        if (text) {
                            return <div>
                                {
                                    text.split(',').map(item => <span style={{marginRight: 10}}>
                                        <TheImage src={item} width={80} height={80}/>
                                    </span>)
                                }
                            </div>
                        }
                    }
                },
                {
                    title: "所属类目",
                    key: "goodsClassifyName",
                    dataIndex: "goodsClassifyName",
                },
            ],
            dataSource: [],
            isModalShow: false,
            pageData: {
                pageNo: 1,
                pageSize: 10,
            },
            total: 0,
            disabledKeys: [],
            selectedRows: {},
            selectedRowKeys: [],
            form_show: true,
            searchOption: [
                { field: 'goodsId', label: '商品ID', placeholder: '请输入', required: false, rules: [], type: 'InputNumber', defaultValue: '', stringMode: true },
                { field: 'goodsName', label: '商品名称', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
            ],
            queryForm: {},
            isSortOpen: false,
            mode: null,
            oldGoodsId: null,
            oldSort: null,
        }
    }
    componentDidMount = () => {
    }
    getData = async () => {
        let { pageData: { pageNo, pageSize }, queryForm } = this.state
        const params = {
            pageNo,
            pageSize,
            ...queryForm,
            reviewStatus: 'T',
            goodsStatus: 'Y',
            storeId: '1524601822801633281'
        }
        let res = await apiGetStoreGoodsPage({ ...params })
        if (res.code === 0 && res.data) {
            this.setState({
                dataSource: res.data,
                pageData: {
                    pageNo: res.pageNo,
                    pageSize: res.pageSize
                },
                total: res.totalCount
            })
        }
    }
    setDisData = (data) => {
        this.setState({
            disabledKeys: data.map(item => item.goodsId)
        })
    }
    // 父组件调用打开选择商品弹窗
    openModal = (mode) => {
        this.setState({
            isModalOpen: true,
            mode
        },()=>{
            this.getData()
        })
    }
    onReset() {
        this.setState({
            queryForm: {}
        }, () => {
            this.pageChange(1, 10)
        })
    }
    onFormSearch(values){
        this.setState({
            pageData: {pageNo:1,pageSize:10},
            queryForm: values
        },()=>{
            this.getData()
        })
    }
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo,
                pageSize
            }
        }, () => {
            this.getData()
        })
    };
    // 勾选商品
    onSelectChange = (selectedRowKeys) => {
        this.setState({
            selectedRowKeys: selectedRowKeys
        })
    }
    // 父组件调用打开排序弹窗
    openSortModal = (mode,goodId) => {
        this.setState({
            mode,
            selectedRowKeys: [goodId],
            oldGoodsId: goodId,
        },()=>{
            this.selectedGoodOk()
        })
    }
    // 打开排序弹窗
    selectedGoodOk = () => {
        let { selectedRowKeys,mode,oldSort } = this.state;
        if (selectedRowKeys.length === 0) {
            message.error('请选择商品')
            return
        }
        apiGetHomeGoodsSortDetail({
            goodsId: selectedRowKeys[0]
        }).then(res=>{
            this.setState({
                isSortOpen: true,
                selectedRows: res.data
            },()=>{
                setTimeout(()=>{
                    let sort = mode === 'change' ? oldSort : res.data.homeGoodsSort
                    this.sortFormRef.setFieldsValue({
                        sort
                    })
                },100)
            })
        })
    }
    // 提交要添加的商品
    addGood = () => {
        let { selectedRowKeys, mode, oldGoodsId } = this.state;
        this.sortFormRef.validateFields().then(formData=>{
            let params = {
                goodsId: selectedRowKeys[0],
                sort: formData.sort
            }
            if (mode === 'add'){
                params.type = 'A'
            }
            else {
                params.type = 'U'
                params.oldGoodsId = oldGoodsId
            }

            console.log(params)
            apiAddHomeGoodsSort(params).then(res=>{
                if (res.code === 0){
                    message.success('操作成功')
                    this.setState({
                        isSortOpen: false,
                        isModalOpen: false,
                        selectedRowKeys: [],
                        selectedRows: {},
                        queryForm: {},
                        pageData: {
                            pageNo: 1,
                            pageSize: 10,
                        },
                    })
                    this.props.refresh()
                }
            })
        })
    }
    // 更改商品
    changeGood = () => {
        this.setState({
            isSortOpen: false,
            isModalOpen: true,
            mode: 'change',
            oldSort: this.sortFormRef.getFieldValue('sort')
        },()=>{
            this.getData()
        })
    }
    render() {
        const {
            isModalOpen,
            dataSource,
            pageData,
            columns,
            searchOption,
            form_show,
            total,
            selectedRowKeys,
            selectedRows,
            isSortOpen,
            disabledKeys,
            mode
        } = this.state
        const rowSelection = {
            type: 'radio',
            selectedRowKeys,
            hideSelectAll: true,
            preserveSelectedRowKeys: true,
            onChange: this.onSelectChange,
            getCheckboxProps: (record) => {
                return { disabled: disabledKeys.includes(record.goodsId) }
            }
        }
        const formItemLayout = {
            labelCol: {
                span: 6,
            },
            wrapperCol: {
                span: 14,
            },
        };
        return (
            <div>
                <Modal
                    title="选择商品"
                    visible={isModalOpen}
                    onOk={this.selectedGoodOk}
                    onCancel={()=>this.setState({
                        isModalOpen: false,
                        selectedRowKeys: [],
                        queryForm: {},
                        pageData: {
                            pageNo: 1,
                            pageSize: 10,
                        },
                    })}
                    width={1200}
                    maskClosable={false}
                    destroyOnClose={true}
                >
                    <TheQueryForm
                        ref={(ref) => this.queryFormRef = ref}
                        show={form_show}
                        option={searchOption}
                        onGetValues={(values) => this.onFormSearch(values)}
                        onReset={(values) => this.onReset(values)}
                    >
                    </TheQueryForm>
                    <TheTable
                        scroll={{ x: "max-content", y: '63vh' }}
                        rowSelection={rowSelection}
                        columns={columns}
                        rowKey={'goodsId'}
                        dataSource={dataSource}
                    />
                    <ThePagination
                        pageNo={pageData.pageNo}
                        pageSize={pageData.pageSize}
                        total={total}
                        pageChange={this.pageChange}
                    />
                </Modal>
                <Modal
                    title={mode !== 'add' ? "修改":"排序"}
                    visible={isSortOpen}
                    width={600}
                    onCancel={()=>this.setState({isSortOpen: false})}
                    maskClosable={false}
                    destroyOnClose={true}
                    footer={[
                        <Button key="back" onClick={()=>this.setState({isSortOpen: false})}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" onClick={this.addGood}>
                            确定
                        </Button>,
                        mode === 'edit' && <Button
                            onClick={this.changeGood}
                        >
                            更换商品
                        </Button>,
                    ]}
                >
                    <Form
                        ref={(ref)=>this.sortFormRef=ref}
                        {...formItemLayout}
                    >
                        <Form.Item label="商品名称">
                            <span className="ant-form-text">{selectedRows.goodsName}</span>
                        </Form.Item>
                        <Form.Item label={"排序"} name="sort" rules={[
                            {
                                required: true,
                                message: '请输入排序',
                            },
                        ]}>
                            <InputNumber placeholder="请输入数字，数字越小排名越靠前，0最小" min={1} max={100} precision={0}/>
                        </Form.Item>
                        <Form.Item label="规格">
                            <Space direction={'vertical'}>
                                {
                                    selectedRows.skuValueList?.map((item, index) => {
                                        return <span key={index} className="ant-form-text">
                                            {item}
                                        </span>
                                    })
                                }
                            </Space>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        );
    }
}

export default SelectGoods;
